<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {CarouselVO, ConfigControllerService, FileControllerService} from "../../../../generated"
import draggable from 'vuedraggable'
import {Rank} from '@element-plus/icons-vue'
import type {UploadFile} from 'element-plus'

// 轮播图管理
interface Carousel {
  id: number
  imageUrl: string
}

const carouselList = ref<Carousel[]>([])

const newCarousel = ref<Carousel>({
  id: 0,
  imageUrl: '',
})

// 文件上传相关
const uploadLoading = ref(false)

const handleUpload = async (file: UploadFile) => {
  if (!file.raw) {
    ElMessage.error('请上传正确的图片')
    return
  }
  uploadLoading.value = true
  try {
    const res = await FileControllerService.uploadImageUsingPost(file.raw)
    if (res.data) {
      newCarousel.value.imageUrl = res.data
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 添加轮播图相关状态
const carouselHasChanges = ref(false)

// 保存轮播图顺序
const saveCarousel = async () => {
  try {
    const imageList = carouselList.value.map(item => item.imageUrl)
    const res = await ConfigControllerService.updateCarouselUsingPost({
      imageList
    })
    if (res.data) {
      ElMessage.success('保存成功')
      await listCarousel()
      carouselHasChanges.value = false
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 添加轮播图
const addCarousel = () => {
  if (!newCarousel.value.imageUrl) {
    ElMessage.warning('请上传图片')
    return
  }

  carouselList.value.push({
    ...newCarousel.value,
    id: carouselList.value.length + 1
  })

  newCarousel.value = {
    id: 0,
    imageUrl: '',
  }

  carouselHasChanges.value = true
  ElMessage.success('添加成功')
}

// 删除轮播图
const deleteCarousel = (id: number) => {
  carouselList.value = carouselList.value.filter(item => item.id !== id)
  carouselHasChanges.value = true
  ElMessage.success('删除成功')
}

const listCarousel = async () => {
  let res = await ConfigControllerService.getCarouselUsingGet();
  if (res.code === 0 && res.data) {
    // 确保将 CarouselVO 转换为字符串
    carouselList.value = res.data.map((item: CarouselVO, index) => ({
      id: index + 1,
      imageUrl: item as string
    }))
  }
}

onMounted(() => {
  listCarousel()
})
</script>

<template>
  <el-card class="manage-section">
    <template #header>
      <div class="card-header">
        <span>轮播图管理</span>
        <div class="header-actions">
          <el-button
              type="primary"
              :disabled="!carouselHasChanges"
              @click="saveCarousel"
          >
            保存修改
          </el-button>
        </div>
      </div>
    </template>

    <!-- 添加上传表单 -->
    <el-form :model="newCarousel" label-width="100px" class="upload-form">
      <el-form-item label="图片">
        <el-upload
            class="upload-demo"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            :on-change="(file: UploadFile) => handleUpload(file)"
        >
          <template #trigger>
            <el-button :loading="uploadLoading" type="primary">选择图片</el-button>
          </template>
        </el-upload>
        <el-input
            v-model="newCarousel.imageUrl"
            placeholder="或直接输入图片URL"
            class="url-input"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addCarousel">添加轮播图</el-button>
      </el-form-item>
    </el-form>

    <!-- 轮播图列表 -->
    <draggable
        v-model="carouselList"
        item-key="id"
        handle=".drag-handle"
        :animation="150"
        ghost-class="ghost-class"
    >
      <template #item="{ element }">
        <div class="carousel-item">
          <div style="display: flex; align-items: center; gap: 15px">
            <el-icon class="drag-handle">
              <Rank/>
            </el-icon>
            <el-image :src="element.imageUrl" style="width: 100px; height: 50px"/>
          </div>
          <el-button
              type="danger"
              size="small"
              @click="deleteCarousel(element.id)"
          >
            删除
          </el-button>
        </div>
      </template>
    </draggable>
  </el-card>
</template>

<style scoped>
.manage-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  font-weight: bold;
}

.upload-form {
  margin-bottom: 20px;
  max-width: 600px;
}

.url-input {
  margin-top: 10px;
}

.carousel-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
  gap: 15px;
  justify-content: space-between;
}

.carousel-item .drag-handle {
  cursor: move;
  color: #909399;
}

.header-actions {
  display: flex;
  gap: 10px;
}

:deep(.ghost-class) {
  opacity: 0.5;
  background: #c8ebfb;
  border: 1px dashed #409eff;
}
</style>